package com.wn.common.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import sun.misc.BASE64Decoder;

import java.io.ByteArrayInputStream;

/**
 * @BelongsProject: shared_parking
 * @BelongsPackage: com.wn.common.util
 * @Author: 廖刚
 * @CreateTime: 2020-06-16 11:25
 * @Description: 关于文件的工具类
 */
public class FileUtil {

    // Endpoint以杭州为例，其它Region请按实际情况填写。
    private static String endpoint = "http://oss-cn-beijing.aliyuncs.com";
    // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
    private static String accessKeyId = "LTAI4G3r15F3Ybkh9NTfFSt4";
    private static String accessKeySecret = "7vmyM5bxgwcySyH7GAalJl8IoMBB2h";
    private static String bucketName = "shared-parkin";

    private static String imgHead = "https://shared-parkin.oss-cn-beijing.aliyuncs.com/";

    /**
     *
     * @param imgStr 图片的base64字符串形式，需要对其截取
     * @return oos中图片地址
     */
    public static String uploadImage(String imgStr){
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        String path = null;
        try {
            int indexOf = imgStr.indexOf("base64");

            String base64ImgStr = imgStr.substring(indexOf+7);
            // 上传Byte数组。
            byte[] content = new BASE64Decoder().decodeBuffer(base64ImgStr);
            String key = "img/" + System.currentTimeMillis() + ".jpg";
            //PutObjectResult putObjectResult = ossClient.putObject(bucketName, key, new ByteArrayInputStream(content));
            ObjectMetadata meta = new ObjectMetadata();
            meta.setContentType("image/jpg");
            ossClient.putObject(bucketName, key, new ByteArrayInputStream(content), meta);
            // 关闭OSSClient。
            ossClient.shutdown();
            //https://shared-parkin.oss-cn-beijing.aliyuncs.com/img/1592279963201.jpg

            path = imgHead +key ;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return path;
    }


}
